<template>
    <component :is="name" v-bind="attributes" v-model="widgetValue" v-on="listenerEvent">
        <template v-for="(value, key) in validSlots" v-slot:[key]>
            <virtual-node v-if="key !== 'default'" :render="value" />
        </template>
        <template v-if="validSlots.default">
            <virtual-node :render="validSlots.default" />
        </template>
    </component>
</template>

<script>
import attributes from "./attributes";
import customAttributes from "../../custom/attributes";

export default {
    name: "Widget",
    model: {
        prop: 'value',
        event: 'changeValue',
    },
    components: {
        VirtualNode: () => import('../../custom/VirtualNode'),
    },
    props: {
        name: {
            type: String,
            required: true,
            default: 'div',
        },
        value: {
            type: [Number, String, Array],
            default: null,
        },
        attributes: {
            type: Object,
            default: null,
        },
        disabled: {
            type: Boolean,
            default: null,
        },
        event: {
            type: Object,
            default: null,
        },
        slots: {
            type: Object,
            default: null,
        },
    },
    data() {
        return {
            widgetValue: null,
        };
    },
    computed: {
        listenerEvent() {
            let listener = $.extend({}, this.$listeners);
            let defaultProps = attributes[this.name] || customAttributes[this.name] || {};
            if (defaultProps.listenerEvent && this.event) {
                for (let ev in defaultProps.listenerEvent) {
                    listener[ev] = event => {
                        typeof this.event[ev] === 'function' && this.event[ev].call(this, event);
                    };
                }
            }
            return listener;
        },
        validSlots() {
            return this.slots || {};
        },
    },
    watch: {
        value: {
            handler() {
                this.widgetValue = this.value;
            },
            deep: true,
            immediate: true,
        },
        widgetValue: {
            handler() {
                this.$emit('changeValue', this.widgetValue);
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
    },
}
</script>

<style scoped lang="less">

</style>